<template>
  <div class="feedback-list-container">
    <h1>反馈管理</h1>
    <div class="chart-container">
      <h2>反馈统计</h2>
      <div id="feedback-chart" style="width: 100%; height: 300px;"></div>
    </div>
    <el-divider />
    <el-space wrap>
      <el-card v-for="feedback in feedbackList" :key="feedback.id" class="feedback-card">
        <template #header>
          <div class="card-header">
            <span>{{ feedback.title || '无标题反馈' }}</span>
            <el-button class="button" text @click="showDetailDrawer(feedback.id)">查看详情</el-button>
          </div>
        </template>
        <p>用户: {{ feedback.userName || '匿名用户' }}</p>
        <p>评分: <el-rate v-model="feedback.rating" disabled show-score text-color="#ff9900" /></p>
        <p>状态: <el-tag :type="feedback.status === 'replied' ? 'success' : 'info'">{{ feedback.status === 'replied' ? '已回复' : '待处理' }}</el-tag></p>
        <p>提交时间: {{ feedback.createdAt }}</p>
      </el-card>
      <p v-if="feedbackList.length === 0">暂无反馈信息。</p>
    </el-space>

    <!-- 反馈详情抽屉 -->
    <el-drawer
      v-model="detailDrawerVisible"
      :title="currentFeedback ? currentFeedback.title : '反馈详情'"
      direction="rtl"
      size="50%"
      :before-close="handleDetailDrawerClose"
    >
      <div v-if="currentFeedback" class="feedback-detail-content">
        <p><strong>反馈ID:</strong> {{ currentFeedback.id }}</p>
        <p><strong>用户ID:</strong> {{ currentFeedback.userId }}</p>
        <p><strong>用户名:</strong> {{ currentFeedback.userName }}</p>
        <p><strong>评分:</strong> <el-rate v-model="currentFeedback.rating" disabled show-score text-color="#ff9900" /></p>
        <p><strong>反馈内容:</strong> {{ currentFeedback.content }}</p>
        <p><strong>提交时间:</strong> {{ currentFeedback.createdAt }}</p>
        <p><strong>状态:</strong> <el-tag :type="currentFeedback.status === 'replied' ? 'success' : 'info'">{{ currentFeedback.status === 'replied' ? '已回复' : '待处理' }}</el-tag></p>
        
        <div v-if="currentFeedback.reply">
          <el-divider />
          <p><strong>管理员回复:</strong> {{ currentFeedback.reply }}</p>
          <p><strong>回复管理员ID:</strong> {{ currentFeedback.repliedByAdminId }}</p>
        </div>

        <el-divider />
        <div class="reply-section">
          <h3>回复反馈</h3>
          <el-input
            v-model="replyContent"
            :rows="4"
            type="textarea"
            placeholder="请输入回复内容"
          />
          <el-button type="primary" @click="submitReply" :loading="submitting" class="submit-button">提交回复</el-button>
        </div>
      </div>
      <el-empty v-else description="未找到反馈信息" />
    </el-drawer> 
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElRate, ElTag, ElDrawer, ElDivider } from 'element-plus';
import { getFeedbackList, getFeedbackInfo } from '@/api/feedback'
import { formatDate } from '@/utils/formatDate';
import * as echarts from 'echarts';

const feedbackList = ref([]);
const loading = ref(true);
const detailDrawerVisible = ref(false);
const currentFeedback = ref(null);
const replyContent = ref('');
const submitting = ref(false);

const feedbackInfo = ref(null); // 用于存储反馈统计信息
let feedbackChart = null; // Echarts 实例
const pageParams = ref({
  pageNum: 1,
  pageSize: 10
})

// 模拟获取反馈列表
const fetchFeedbackList = async () => {
  loading.value = true;
  try {
    const data = await getFeedbackList(pageParams.value)
    feedbackList.value = data.list;
    console.log(data)
  } catch (error) {
    ElMessage.error(error || '获取失败')
  }
  finally {
    loading.value = false;
  }
};

// 模拟获取反馈统计信息
const fetchFeedbackInfo = async () => {
  loading.value = true;
  try {
    const data = await getFeedbackInfo()
    feedbackInfo.value = data;
  } catch (error) {
    ElMessage.error(error || '获取失败')
  }
  finally {
    loading.value = false;
  }
};

// 初始化 Echarts 图表
const initChart = () => {
  const chartDom = document.getElementById('feedback-chart');
  if (chartDom) {
    if (feedbackChart) {
      feedbackChart.dispose(); // 销毁之前的实例，避免内存泄漏
    }
    feedbackChart = echarts.init(chartDom);
    if (feedbackInfo.value) {
      const option = {
        title: {
          text: '用户反馈情绪分析',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['积极反馈', '消极反馈']
        },
        series: [
          {
            name: '反馈类型',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '30',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: feedbackInfo.value.positiveCount, name: '积极反馈' },
              { value: feedbackInfo.value.negativeCount, name: '消极反馈' }
            ]
          }
        ]
      };
      feedbackChart.setOption(option);
    }
  }
};

const showDetailDrawer = async (id) => {
  // 从模拟数据中查找详情
  const foundFeedback = feedbackList.value.find(f => f.id === id);
  if (foundFeedback) {
    currentFeedback.value = foundFeedback;
    replyContent.value = ''; // 每次打开抽屉时清空回复框内容
    detailDrawerVisible.value = true;
  } else {
    ElMessage.error('未找到该反馈信息。');
  }
};

const handleDetailDrawerClose = (done) => {
  currentFeedback.value = null;
  replyContent.value = '';
  done();
};

const submitReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('回复内容不能为空。');
    return;
  }
  if (!currentFeedback.value || !currentFeedback.value.id) {
    ElMessage.error('未选中反馈，无法提交回复。');
    return;
  }
  submitting.value = true;
  await new Promise(resolve => setTimeout(resolve, 500));

  const index = feedbackList.value.findIndex(f => f.id === currentFeedback.value.id);
  if (index !== -1) {
    feedbackList.value[index].reply = replyContent.value;
    feedbackList.value[index].status = 'replied';
    feedbackList.value[index].repliedByAdminId = 'admin_current';
  }

  ElMessage.success('回复成功！');
  detailDrawerVisible.value = false;
  currentFeedback.value = null;
  replyContent.value = '';
  submitting.value = false;
};

onMounted(async () => {
  await fetchFeedbackList();
  await fetchFeedbackInfo();
  initChart(); // 初始化图表
});

</script>

<style scoped>
.feedback-list-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.chart-container {
  margin-bottom: 25px;
  padding: 25px;
  border: none;
  border-radius: 15px;
  background-color: #ffffff;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.feedback-card {
  width: 300px;
  margin-bottom: 25px;
  border: none;
  border-radius: 15px;
  background-color: #ffffff;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  padding: 15px;
}

.feedback-card:hover {
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-6px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.card-header span {
  font-size: 19px;
  font-weight: bold;
  color: #303133;
}

.feedback-card p {
  margin-bottom: 10px;
  font-size: 15px;
  color: #606266;
  line-height: 1.6;
}

.feedback-detail-content {
  padding: 30px;
  font-size: 16px;
  color: #303133;
  background-color: #fcfcfc;
  border-radius: 10px;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.03);
}

.feedback-detail-content p {
  margin-bottom: 12px;
  line-height: 1.8;
}

.feedback-detail-content p strong {
  color: #2b85e4;
  margin-right: 8px;
  font-weight: 600;
}

.el-rate {
  vertical-align: middle;
  margin-top: -3px;
}

.el-tag {
  font-size: 14px;
  padding: 0 8px;
  height: 28px;
  line-height: 26px;
}

.el-divider {
  margin: 25px 0;
  border-top: 1px dashed #dcdfe6;
}

.reply-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.reply-section h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 18px;
}

.submit-button {
  margin-top: 20px;
  width: 100%;
}
</style>